package speed2010.middleware.comunicacao;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import speed2010.middleware.serviceOverlay.node.Node;

public class SocketServer {

	private Node parentNode = null;
	private ServerSocket serverSocket = null;
	private Socket clientSocket = null;
	private boolean destroyed = false;

	public SocketServer(int porta, Node parentNode) {
		this.parentNode = parentNode;
		while (!destroyed) {
			try {
				this.open(porta);
			} catch (IOException e) {
				e.printStackTrace();
				System.exit(1);
			}
		}
	}

	private void open(int porta) throws IOException {
		
		serverSocket = new ServerSocket(porta);
				
		try {			
			System.out.println("Server listening on port " + porta +". Waiting for connections.");
			while (!destroyed) {
				clientSocket = serverSocket.accept();
				// System.out.println("Accepted a connection from: "
				// + client.getInetAddress() + " - LocalPort: "
				// + client.getLocalPort() + " - RemotePort: "
				// + client.getPort());
				new Thread(new SocketServerConnection(clientSocket,
						this.parentNode)).start();
			}
		} catch (Exception e) {
			System.out.println("Port:"+porta);
			e.printStackTrace();
		}
	}

	public void close() {
		try {
			this.destroyed = true;
			this.serverSocket.close();
			System.out.println("Fechou o socket");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
